﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data;
using System.Data.SqlClient;

namespace _9___ATM
{
    class Program
    {
        static void Main(string[] args)
        {
            string card = "4235";
            string pin = "5434";
            decimal cash = 121231233m;


            SqlConnection con = new SqlConnection(@"Server=.\SQLEXPRESS;Database=ATM;Integrated Security=true");
            con.Open();
            using (con)
            {
                SqlTransaction trans = con.BeginTransaction(IsolationLevel.ReadCommitted);
                SqlCommand com = con.CreateCommand();
                com.Transaction = trans;
                try
                {
                    com.CommandText = "SELECT CardCash FROM CardAccounts WHERE CardNumber=@c AND CardPIN=@p";
                    com.Parameters.Add(new SqlParameter("@c", card));
                    com.Parameters.Add(new SqlParameter("@p", pin));
                    SqlDataReader reader = com.ExecuteReader();
                    using (reader)
                    {
                        reader.Read();
                        decimal c = (decimal)reader["CardCash"];
                        if (cash > c)
                        {
                            Console.WriteLine("Cannot complete transaction. Not enough minerals");
                        }
                    }
                    com.CommandText = "UPDATE CardAccounts SET CardCash = CardCash-@lamda WHERE CardNumber=@c AND CardPIN=@p";
                    com.Parameters.Add(new SqlParameter("@lamda", cash));
                    com.ExecuteNonQuery();
                    trans.Commit();
                }
                catch (Exception e)
                {
                    Console.WriteLine("Exception: {0}", e.Message);
                    trans.Rollback();
                    Console.WriteLine("Transaction cancelled.");
                }

            }
        }
    }
}
